package com.linkq.ipinyin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linkq.core.base.BaseService;
import com.linkq.ipinyin.dao.ExamPaperDao;
import com.linkq.ipinyin.mapper.ExamPaperMapper;
import com.linkq.ipinyin.mapper.ExamPaperQuestionCustomerAnswerMapper;
import com.linkq.ipinyin.mapper.QuestionMapper;
import com.linkq.ipinyin.mapper.TextContentMapper;
import com.linkq.ipinyin.model.ExamPaper;
import com.linkq.ipinyin.model.ExamPaperQuestionCustomerAnswer;
import com.linkq.ipinyin.model.Question;
import com.linkq.ipinyin.model.TextContent;
import com.linkq.ipinyin.model.vo.ExamAnswerVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @FileName ExamPaperService
 * @Description
 * @Author wangpeng
 * @date 2024-11-26
 **/

@Service
@Transactional
public class ExamPaperService extends BaseService<ExamPaperDao, ExamPaper> {
    @Autowired
    private ExamPaperMapper examPaperMapper;
    @Autowired
    private TextContentMapper textContentMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private ExamPaperQuestionCustomerAnswerMapper examPaperQuestionCustomerAnswerMapper;

    public JSONObject submitExam(ExamAnswerVo examAnswerVo) {
        List<ExamPaperQuestionCustomerAnswer> answers = new ArrayList<>();
        ExamPaper examPaper = examPaperMapper.selectById(examAnswerVo.getExamId());
        examAnswerVo.getAnswers().forEach(answer -> {
            ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = new ExamPaperQuestionCustomerAnswer();
            Question question = questionMapper.selectById(answer.getQuestionId());
            examPaperQuestionCustomerAnswer.setExamPaperId(examPaper.getId());
            examPaperQuestionCustomerAnswer.setAnswer(answer.getAnswer());
            examPaperQuestionCustomerAnswer.setQuestionScore(question.getScore());
            examPaperQuestionCustomerAnswer.setQuestionTextContentId(question.getInfoTextContentId());
            examPaperQuestionCustomerAnswer.setCreateUser(examAnswerVo.getUserId());
            Integer questionType = question.getQuestionType();
            if (questionType == 1) {// 单选题
                if (StringUtils.equals(answer.getAnswer(), question.getCorrect())) {
                    examPaperQuestionCustomerAnswer.setDoRight(true);
                    examPaperQuestionCustomerAnswer.setCustomerScore(question.getScore());
                } else {
                    examPaperQuestionCustomerAnswer.setDoRight(false);
                    examPaperQuestionCustomerAnswer.setCustomerScore(0);
                }
            } else if (questionType == 4){ // 填空题， 多个空以**分隔
                List<String> answerList = Arrays.asList(answer.getAnswer().split("\\*\\*"));
                TextContent textContent = textContentMapper.selectById(question.getInfoTextContentId());
                JSONObject content = JSON.parseObject(textContent.getContent());
                JSONArray questionItemObjects = JSONArray.parseArray(content.getString("questionItemObjects"));
                questionItemObjects.sort(Comparator.comparingInt(o -> JSONObject.parseObject(o.toString()).getInteger("prefix")));
                int score = 0;
                boolean doRight = true;
                int[] blanks = new int[questionItemObjects.size()];
                for(int i = 0; i < questionItemObjects.size(); i++) {
                    JSONObject item = JSON.parseObject(questionItemObjects.getString(i));
                    if (StringUtils.equals(item.getString("content"), answerList.get(i))) {
                        score += item.getInteger("score");
                        blanks[i] = 1;
                    } else {
                        doRight = false;
                    }
                }
                examPaperQuestionCustomerAnswer.setBlanks(blanks);
                examPaperQuestionCustomerAnswer.setDoRight(doRight);
                examPaperQuestionCustomerAnswer.setCustomerScore(score);
            } else if (questionType == 6) {
                examPaperQuestionCustomerAnswer.setDoRight(answer.getIsTrue());
                examPaperQuestionCustomerAnswer.setCustomerScore(answer.getIsTrue() ? question.getScore() : 0);
            }
            examPaperQuestionCustomerAnswerMapper.insert(examPaperQuestionCustomerAnswer);
            answers.add(examPaperQuestionCustomerAnswer);
        });
        JSONObject result = new JSONObject();
        int totalScore = answers.stream().mapToInt(ExamPaperQuestionCustomerAnswer::getCustomerScore).sum();
        result.put("totalScore", totalScore);
        result.put("answerDetail", answers);
        return result;
    }

    public List<ExamPaper> getExamByCondition(ExamPaper examPaper) {
        LambdaQueryWrapper<ExamPaper> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(examPaper.getGradeLevel() != null, ExamPaper::getGradeLevel, examPaper.getGradeLevel());
        queryWrapper.eq(examPaper.getId() != null, ExamPaper::getId, examPaper.getId());
        queryWrapper.like(StringUtils.isNotBlank(examPaper.getName()), ExamPaper::getName, examPaper.getName());
        return examPaperMapper.selectList(queryWrapper);
    }

    public JSONArray getWrongQuestion(ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer) {
        List<ExamPaperQuestionCustomerAnswer> answers = examPaperQuestionCustomerAnswerMapper.selectList(Wrappers
                .<ExamPaperQuestionCustomerAnswer>lambdaQuery()
                .eq(examPaperQuestionCustomerAnswer.getCreateUser() != null, ExamPaperQuestionCustomerAnswer::getCreateUser, examPaperQuestionCustomerAnswer.getCreateUser())
                .eq(examPaperQuestionCustomerAnswer.getExamPaperId() != null, ExamPaperQuestionCustomerAnswer::getExamPaperId, examPaperQuestionCustomerAnswer.getExamPaperId()));

        JSONArray result = new JSONArray();
        if (CollectionUtils.isNotEmpty(answers)) {
            answers.forEach(answer -> {
                int examPaperId = answer.getExamPaperId();
                ExamPaper examPaper = examPaperMapper.selectById(examPaperId);
                int textContentId = answer.getQuestionTextContentId();
                TextContent textContent = textContentMapper.selectById(textContentId);
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(answer);
                jsonObject.put("examPaper", examPaper);
                jsonObject.put("questionTextContent", textContent);
                result.add(jsonObject);
            });
        }
        return result;
    }
}
